package com.gaoxk.shutdownfiter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
//可以用kill pid 优雅关闭
@Component
public class GracefulShutdownHook {
    private static final Logger log = LoggerFactory.getLogger(GracefulShutdownHook.class);

    @Autowired
    private ShutdownFilter shutdownFilter;

    @Value("${server.shutdowntimeout:30000}")
    private long timeout;

    @Value("${server.shutdownchecktime:1000}")
    private long interval;

    @PostConstruct
    public void registerShutdownHook() {
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            // 1. 触发过滤器开始拒绝新请求
            shutdownFilter.startShutdown();
            log.warn("开始拒绝新请求，等待未完成交易...");

            // 2. 等待活跃请求数归零（最多等30秒）
//            long timeout = 30_000; // 超时时间：30秒
//            long interval = 1_000; // 检查间隔：1秒
            long start = System.currentTimeMillis();

            while (shutdownFilter.getActiveRequests() > 0) {
                if (System.currentTimeMillis() - start > timeout) {
                    log.warn("等待超时，强制关闭剩余请求");
                    break;
                }
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }

            log.warn("所有交易处理完毕，服务关闭");
        }));
    }
}
